package com.alibaba.cirtus.ots.application.adapter.ability.facade.serviceV2.sap;

import com.alibaba.cirtus.ots.application.adapter.ability.facade.serviceV2.otw.common.OtwConstant;
import com.alibaba.cirtus.ots.application.adapter.ability.facade.serviceV2.sap.innerService.SalesOrderService;
import com.alibaba.cirtus.ots.application.adapter.ability.model.Result;
import com.alibaba.cirtus.ots.application.adapter.ability.model.enums.MnSAPStatus;
import com.alibaba.cirtus.ots.application.adapter.ability.model.response.OrderAndDetailResponse;
import com.alibaba.cirtus.ots.application.adapter.ability.utils.HttpTokenUtil;
import com.alibaba.cirtus.ots.application.adapter.ability.utils.HttpUtils;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.epoch.app.otsapplicationadaptersdk.contants.OtsApplicationAdapterSdkConstants;
import com.epoch.app.otsapplicationadaptersdk.mnsapif047v2.dto.CallbackRequest;
import com.epoch.app.otsapplicationadaptersdk.mnsapif047v2.service.MnSapIf047V2Service;
import com.epoch.app.otsapplicationadaptersdk.sap.MnSapCommResponse;
import com.epoch.app.otsapplicationadaptersdk.sap.MnSapCommSDO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Component
@Primary
public class MnSapIf047V2ServiceImpl implements MnSapIf047V2Service {
    private final Log log = Log.getLogger(MnSapIf047V2ServiceImpl.class);

    @Autowired
    private HttpUtils httpUtils;
    @Resource
    private SalesOrderService salesOrderService;
    @Override
    public MnSapCommResponse callback(CallbackRequest callbackRequest) {
        log.info("MnSapIf047V2ServiceImpl callBack param:{}", JSON.toJSONString(callbackRequest));
        MnSapCommResponse mnSapCommResponse = new MnSapCommResponse();
        List<MnSapCommSDO> dataList = new ArrayList<>();
        try {
            JSONObject message = JSON.parseObject(callbackRequest.getMessage());

            JSONArray data = message.getJSONArray("data");
            for (int i = 0; i < data.size(); i++) {
                JSONObject dataItem = data.getJSONObject(i);
                JSONArray items = getItem(dataItem);
                for (int j = 0; j < items.size(); j++) {
                    JSONObject item = items.getJSONObject(j);

                    String outerItemKey = item.getString("SAPItemKey");
                    if(item.containsKey("STATUS") && "E".equals(item.getString("STATUS"))){
                        OrderAndDetailResponse orderAndDetail = salesOrderService.getOrderAndDetail(outerItemKey);
                        if(Objects.isNull(orderAndDetail)){
                            MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                            mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
                            mnSapCommSDO.setErrCode(OtwConstant.ORDER_001_01_01_001);
                            mnSapCommSDO.setMessage("outerItemKey ="+outerItemKey+" not find sales order");
                            dataList.add(mnSapCommSDO);
                            break;
                        }
                        String redisKey = String.format("%s-%s", "confirmQuantitySync", orderAndDetail.getOrder().getOrderBizId());
                        //释放锁
                        salesOrderService.unlock(redisKey);
                        MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
                        mnSapCommSDO.setStatus(MnSAPStatus.SUCCESS.getCode());
                        dataList.add(mnSapCommSDO);
                        break;
                    }

                }

            }
            // 不管callback返回成功还是失败，都在执行记录里面记录一下callback日志
            toBcLink(message);
        } catch (Exception e) {
            log.error("MnSapIf021V2ServiceImpl callBack error", e);
            MnSapCommSDO mnSapCommSDO = new MnSapCommSDO();
            mnSapCommSDO.setStatus(MnSAPStatus.ERROR.getCode());
            mnSapCommSDO.setErrCode(OtwConstant.ORDER_001_01_01_001);
            mnSapCommSDO.setMessage(MnSAPStatus.ERROR.getMsg());
            dataList.add(mnSapCommSDO);
        }
        mnSapCommResponse.setData(dataList);
        return mnSapCommResponse;
    }
    private JSONArray getItem(JSONObject dataItem){
        JSONArray items = new JSONArray();
        try{
            items = dataItem.getJSONArray("Item");
        }catch (Exception e ){
            log.error("MnSapIf047V2ServiceImpl callBack getJSONArray error ",e);
            JSONObject itemOne = dataItem.getJSONObject("Item");
            items.add(itemOne);
        }
        return items;
    }
    private void toBcLink(JSONObject message) {
        log.info("MnSapIf047V2ServiceImpl toBcLink param:{}", JSON.toJSONString(message));
        try {
            Map<String, String> header = HttpTokenUtil.generateHttpHeader();
            String urlPrefix = OtsApplicationAdapterSdkConstants.urlPrefix();
            String url = urlPrefix + "api/mn_bc_link/saveTaskLog";

            JSONObject messageHeader = message.getJSONObject("MessageHeader");
            JSONObject data = message.getJSONArray("data").getJSONObject(0);
            JSONArray items = getItem(data);
            JSONObject item = new JSONObject();
            String key = messageHeader.getString("MESSAGEID");
            for (int i = 0; i < items.size(); i++) {
                JSONObject itemTemp = items.getJSONObject(i);
                if (StringUtils.isNotBlank(itemTemp.getString("SAPItemKey"))) {
                    key = itemTemp.getString("SAPItemKey");
                }
                if("E".equals(itemTemp.getString("STATUS"))){
                    item = itemTemp;
                    break;
                }
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("key", key);
            jsonObject.put("apiCode", "MN-SAP-IF-047-CALLBACK");
            jsonObject.put("apiDesc", "中台确认数量同步SAP callback");
            jsonObject.put("callback", true);
            jsonObject.put("errorCode", item.getString("STATUS"));
            jsonObject.put("errorMessage", item.getString("MESSAGE"));
            jsonObject.put("executeStatus", "E".equals(item.getString("STATUS")) ? 0 : 1);
            jsonObject.put("messageId", messageHeader.getString("MESSAGEID"));
            jsonObject.put("requestInfo", JSON.toJSONString(message));
            jsonObject.put("sourceClient", "SAP");
            jsonObject.put("targetClient", "ZT");

            log.info("MnSapIf047V2ServiceImpl toBcLink call bc link interface,url:{}, header:{}, " + "param:{}", url,
                header, jsonObject);
            ResponseEntity<Result> post = httpUtils.post(url, header, jsonObject,
                com.alibaba.cirtus.ots.application.adapter.ability.model.Result.class);
            com.alibaba.cirtus.ots.application.adapter.ability.model.Result result = post.getBody();
            log.info("MnSapIf047V2ServiceImpl toBcLink result:{}", JSON.toJSONString(result));
        } catch (Exception e) {
            log.error("MnSapIf047V2ServiceImpl toBcLink error", e);
        }
    }


}
